# coding:utf-8
from odoo import models, fields, api, _
from odoo.osv import expression


class OLResPartner(models.Model):
    _name = 'res.partner'
    _inherit = 'res.partner'

    property_product_pricelist_ids = fields.Many2many('product.pricelist', 'partner_price_list_rel',
                                                      'price_list_id', 'partner_id', string='Price List Set')
    # section_leader_ids = fields.Many2many('res.users', 'customer_team_rel', 'partner_id', 'user_id', string='Sales Team Leaders')
    country = fields.Many2one('partner.categ', string=u'国别', domain="[('categ', '=', 'country')]")
    region = fields.Many2one('partner.categ', string=u'区域', domain="[('categ', '=', 'region')]")
    priority = fields.Many2one('partner.categ', string=u'重要性', domain="[('categ', '=', 'priority')]")
    capability = fields.Many2one('partner.categ', string=u'业务量', domain="[('categ', '=', 'capability')]")
    packing_claim = fields.Many2one('partner.categ', string=u'包装要求', domain="[('categ', '=', 'packing_claim')]")
    payment_type = fields.Many2one('partner.categ', string=u'收款方式', domain="[('categ', '=', 'payment_type')]")

    customer_payment_term_ids = fields.Many2many('account.payment.term', 'partner_customer_payment_term_rel',
                                                 'payment_id', 'partner_id', string='Customer Payment Terms')
    vendor_payment_term_ids = fields.Many2many('account.payment.term', 'partner_supplier_payment_term_rel',
                                               'payment_id', 'partner_id', string='Vendor Payment Terms')
    contract_person = fields.Char(u'联系人')

    @api.onchange('customer_payment_term_ids', 'vendor_payment_term_ids')
    def _check_not_exist_pricelist(self):
        if self.property_payment_term_id.id not in self.customer_payment_term_ids.mapped('id'):
            self.property_payment_term_id = False
        if self.property_supplier_payment_term_id.id not in self.vendor_payment_term_ids.mapped('id'):
            self.property_supplier_payment_term_id = False

    @api.onchange('property_product_pricelist_ids')
    def _check_not_exist_pricelist(self):
        if self.property_product_pricelist.id not in self.property_product_pricelist_ids.mapped('id'):
            self.property_product_pricelist = False

    @api.multi
    def name_get(self):
        res = []
        for partner in self:
            name = partner.ref and '[%s] %s' % (partner.ref, partner.name) or partner.name or ''

            if partner.company_name or partner.parent_id:
                if not name and partner.type in ['invoice', 'delivery', 'other']:
                    name = dict(self.fields_get(['type'])['type']['selection'])[partner.type]
                if not partner.is_company:
                    name = partner.parent_id.ref \
                           and "[%s] %s, %s" % (partner.parent_id.ref, partner.commercial_company_name or partner.parent_id.name, name) \
                           or "%s, %s" % (partner.commercial_company_name or partner.parent_id.name, name)
            if self._context.get('show_address_only'):
                name = partner._display_address(without_company=True)
            if self._context.get('show_address'):
                name = name + "\n" + partner._display_address(without_company=True)
            name = name.replace('\n\n', '\n')
            name = name.replace('\n\n', '\n')
            if self._context.get('show_email') and partner.email:
                name = "%s <%s>" % (name, partner.email)
            if self._context.get('html_format'):
                name = name.replace('\n', '<br/>')
            res.append((partner.id, name))
        return res

    # @api.model
    # def name_search(self, name, args=None, operator='ilike', limit=100):
    #     """ Returns a list of tupples containing id, name, as internally it is called {def name_get}
    #         result format: {[(id, name), (id, name), ...]}
    #     """
    #     args = args or []
    #     if operator in expression.NEGATIVE_TERM_OPERATORS:
    #         domain = [('ref', operator, name), ('name', operator, name)]
    #     else:
    #         domain = ['|', ('ref', operator, name), ('name', operator, name)]
    #     partner = self.search(expression.AND([domain, args]), limit=limit)
    #     return partner.name_get()

    # def _calc_section(self, section_ids):
    #     leads = []
    #
    #     for section_id in section_ids:
    #         # add parent section
    #         while True:
    #             if section_id.user_id is not None and section_id.user_id.id is not False:
    #                 leads.append(section_id.user_id.id)
    #             if section_id.parent_id is not None and section_id.parent_id.id is not False:
    #                 section_id = section_id.parent_id
    #                 continue
    #             else:
    #                 break
    #     values = {'section_leader_ids': leads}
    #     return values
    #
    # @api.multi
    # def write(self, vals):
    #     for partner in self:
    #         if partner.customer is True and partner.company_type == 'company':
    #             sales_person = partner.user_id.id
    #             if 'user_id' in vals:
    #                 sales_person = vals['user_id']
    #             section_ids = self.env['crm.team'].search(
    #                 ['|', ('user_id', '=', sales_person), ('member_ids', 'in', [sales_person])])
    #             values = self._calc_section(section_ids)
    #             if len(values['section_leader_ids']) > 0:
    #                 vals['section_leader_ids'] = [(4, values['section_leader_ids'])]
    #             else:
    #                 raise Warning(u'请确认销售员属于至少一个销售团队,并且此销售团队需要设定团队领导')
    #     return super(PaulCustomerExtend, self).write(vals)
    #
    # @api.model
    # def create(self, vals):
    #     for partner in self:
    #         if partner.customer is True and partner.company_type == 'company':
    #             section_ids = self.env['crm.team'].search(
    #                 ['|', ('user_id', '=', self._uid), ('member_ids', 'in', [self._uid])])
    #             values = self._calc_section(section_ids)
    #             if len(values['section_leader_ids']) > 0:
    #                 vals['section_leader_ids'] = [(4, values['section_leader_ids'])]
    #             else:
    #                 raise Warning(u'请确认销售员属于至少一个销售团队,并且此销售团队需要设定团队领导')
    #     return super(PaulCustomerExtend, self).create(vals)
